package com.example.gm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.example.gm.entity.ApiResult;
import com.example.gm.entity.GmConst;
import com.example.gm.entity.LoginEntity;
import com.example.gm.entity.MyUserDetails;
import com.example.gm.entity.SecretEntity;
import com.fasterxml.jackson.core.JsonProcessingException;

@Component
public class GmApiService {
	@Autowired
	GmCryptoService gmCryptoService;
	@Autowired
	GmJwtService gmJwtService;

	public ApiResult publickey() throws JsonProcessingException {
		// 提供给前端的sm2公钥
		// 公钥格式： 不压缩标志 04 + hex(X) + hex(Y)
		String key = this.gmCryptoService.getPublicKey();
		return ApiResult.ok(key);
	}

	public ApiResult encrypt(SecretEntity params) throws JsonProcessingException {
		if(params.getMethod()=="sm4") {
			// 使用sm4对称加密
			return this.gmCryptoService.encryptSm4(params.getMessage());
		} else {
			// 使用sm2非对称加密
			return this.gmCryptoService.encryptC1C3C2(params.getMessage());
		}
	}

	public ApiResult decrypt(SecretEntity params) throws JsonProcessingException {
		if(params.getMethod()=="sm4") {
			// 使用sm4对称加密
			return this.gmCryptoService.decryptSm4(params.getMessage());
		} else {
			// 使用sm2非对称加密
			return this.gmCryptoService.decryptC1C3C2(params.getMessage());
		}
	}

	public ApiResult login(LoginEntity params) throws JsonProcessingException {
		SecretEntity secret = new SecretEntity();
		secret.setMethod(params.getMethod());//加密方法
		secret.setMessage(params.getPassword());//密码
		ApiResult result = this.decrypt(secret);//尝试解密
		if(result.getCode()!=GmConst.ERROR_OK)return result;
		
		String username = params.getAccount();//用户名
		String password = result.getMessage();//解密的明文密码
		System.out.println("用户名："+username+", 解密的明文密码："+password);
		return ApiResult.ok(this.createUserDetails(username));
	}

	private MyUserDetails createUserDetails(String username) {		
		MyUserDetails detail = new MyUserDetails();
		detail.setUsername(username);
		detail.setExpire(36000L);
		detail.setToken(this.gmJwtService.createToken(username));
		return detail;
	}
	
}
